<template>
  <div class="comp-container">
    <div class="flex-center">
      <SectionTitle title="关联账号" />
      <PlainCreateBtn v-if="showAddBtn" :disabled="loading" @click="accountDialogShow">选择账号</PlainCreateBtn>
      <PlainCreateBtn v-if="showAddBtn" :disabled="loading" @click="goCreateAccount">新建账号</PlainCreateBtn>
    </div>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="handleSpliceData"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        class="fb-table"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row>
        <EmptyPlaceholder slot="empty" mode="table" />
        <el-table-column label="平台" min-width="120" align="left">
          <template slot-scope="scope">
            <div class="flex-center">
              <PlatformIcon :data="scope.row.platformTypeName" />
              <ToolTip :content="scope.row.platformTypeName" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="账号名称" min-width="180" align="left">
          <template slot-scope="scope">
            <ToolTip
              :content="scope.row.resourceName"
              :is-can-click="!!scope.row.mediumId"
              style="cursor:pointer; color:#406EFF;"
              @handelClick="toResourceDetail(scope.row.mediumId)" />
          </template>
        </el-table-column>
        <el-table-column label="账号ID" min-width="120" align="left">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.resourceId" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="粉丝量" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.fansNum | numberTextFormat(1)" />
          </template>
        </el-table-column>
        <el-table-column label="签约状态" min-width="160" align="left">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.signDetailStatus || scope.row.signDetailStatus === 0" :open-delay="800" class="sign-status-tooltip" placement="top">
              <div slot="content" class="tooltip-content">
                <div class="account-item-tip"> {{ scope.row.signDetailStatus | signStatusFilter }} <br></div>
              </div>
              <StatusText
                :color="getColor(scope.row.signDetailStatus)"
                :text="scope.row.signDetailStatus | signStatusFilter"
              />
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="供应商名称" min-width="110">
          <template slot-scope="scope">
            <ToolTip v-if="scope.row.supplierId" :content="scope.row.cooperation" style="cursor:pointer;color:#406EFF;" @click.native="toSupplierDetail(scope.row.supplierId)"/>
            <div v-else style="color:#999999">未关联</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="签单签约经纪" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.contractBroker" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="签约所属部门" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.signGroupsName" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建人" prop="creator" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.createName" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="创建时间" min-width="160" prop="createTime">
          <template slot-scope="scope">
            <ToolTip :content="formatTime(scope.row.createTime, 'YYYY/MM/DD HH:mm:ss')" />
          </template>
        </el-table-column>
        <el-table-column v-if="showDelBtn || canSyncAccount" label="操作" fixed="right" min-width="80" align="left">
          <template slot-scope="scope">
            <div v-if="showDelBtn" class="button-text" @click="deleteRelated(scope.$index)">删除</div>
            <el-button v-if="canSyncAccount" :disabled="syncDisabled" type="text" @click="handleSync(scope.row)">同步资源</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          v-show="selectedData.length > 10"
          :current-page="currPage"
          :page-size="perPage"
          :total="selectedData.length"
          :small="showMobilePage"
          :page-sizes="[10, 20, 50, 100]"
          :layout="showMobilePage ? 'prev, pager, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>
    <AccountSelection
      ref="accountSelectionRef"
      :visible.sync="showAccountSelection"
      :expend-filter="expendFilter"
      is-contract-module
      @submit="handleAccountSelected"
    />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import AccountSelection from '@/components/resource/AccountSelection';
import PlatformIcon from '@/components/Common/platformIcon';
import { mapState } from 'vuex';
import { format as formatTime } from '@/filters/date';
import { numberTextFormat } from '@/filters/number';
import { signStatusFilter, getSignUpColor } from '@/filters/status';
import { hasRouteAuth } from '@/utils/permission';

export default {
  filters: {
    numberTextFormat,
    signStatusFilter
  },
  components: {
    SectionTitle,
    AccountSelection,
    EmptyPlaceholder,
    PlatformIcon
  },
  model: {
    prop: 'selectedData',
    event: 'changeValue'
  },
  props: {
    selectedData: {
      type: Array,
      default() {
        return [];
      }
    },
    showAddBtn: {
      type: Boolean,
      default: false
    },
    showDelBtn: {
      type: Boolean,
      default: false
    },
    canSyncAccount: {
      type: Boolean,
      default: false
    },
    syncDisabled: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currPage: 1,
      perPage: 10,
      showAccountSelection: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    expendFilter() {
      return [{
        keyword: 'operator', name: '供应商名称', type: 'input', labelWidth: '99px'
      }];
    },
    handleSpliceData() {
      if (!Array.isArray(this.selectedData) || !this.selectedData.length) return [];
      return this.selectedData.slice((this.currPage - 1) * this.perPage, this.currPage * this.perPage);
    }
  },
  created() {
  },
  methods: {
    formatTime,
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(val) {
      this.currPage = val;
    },
    deleteRelated(index) {
      const idx = index + ((this.currPage - 1) * this.perPage);
      this.selectedData.splice(idx, 1);
      if (((this.currPage - 1) * this.perPage) >= this.selectedData.length) {
        this.currPage = 1;
      }
    },
    handleSync(rowData) {
      this.$emit('handleSyncAccount', rowData.mediumId);
    },
    getColor(status) {
      return getSignUpColor(signStatusFilter(status));
    },
    accountDialogShow() {
      this.$refs['accountSelectionRef'].init(this.selectedData);
      this.showAccountSelection = true;
    },
    handleAccountSelected(selectedList) {
      const list = _.cloneDeep(selectedList);
      list.forEach(item => {
        item.fansNum = item.baseInfo.fansNum;
        item.signGroupsName = item.additionalKey.signGroupsName;
        item.contractBroker = item.additionalKey.contractBroker;
      });
      this.$emit('changeValue', list);
      this.showAccountSelection = false;
      this.$nextTick(() => {
        this.currPage = Math.max(Math.ceil(this.selectedData.length / this.perPage), 1);
      });
    },
    // 跳转销售供应商
    toSupplierDetail(channelId) {
      if (channelId) {
        const url = this.$router.resolve({
          name: 'supplierManageDetail',
          params: { id: channelId }
        });
        window.open(url.href, '_blank');
      }
    },
    goCreateAccount() {
      const routeUrl = this.$router.resolve({
        name: 'resource',
        query: { toCreate: 1 }
      });
      window.open(routeUrl.href, '_blank');
    },
    // 账号资源详情
    toResourceDetail(id) {
      if (!hasRouteAuth('medium:resource:admin')) {
        this.$message.warning('暂无资源可读权限，请联系管理员开通');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'detailResource',
        params: { resourceId: id }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.comp-container {
  margin-bottom: 24px;
  .table-container {
    position: relative;
    margin-top: 10px;
  }
}
</style>
